package com.lagou.work3;

import java.io.*;

public class FileOper extends Thread {

    private String srcDir;

    private String desDir;

    public FileOper() {
    }

    public FileOper(String srcDir, String desDir) {
        this.srcDir = srcDir;
        this.desDir = desDir;
    }

    public String getSrcDir() {
        return srcDir;
    }

    public void setSrcDir(String srcDir) {
        this.srcDir = srcDir;
    }

    public String getDesDir() {
        return desDir;
    }

    public void setDesDir(String desDir) {
        this.desDir = desDir;
    }

    @Override
    public void run() {
        try {
            copyDir(this.srcDir,this.desDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyDir(String srcDir, String desDir) throws IOException {
        File srcfile = new File(srcDir);
        File desfile = new File(desDir);
        if (!desfile.exists())//如果目标目录不存在
        {
            desfile.mkdirs();
        }

        File[] files = srcfile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile())//如果是一个文件
                copyFile(files[i].getAbsolutePath(), desDir + "/" + files[i].getName());
            else //如果是一个目录
                copyDir(files[i].getAbsolutePath(), desDir + "/" + files[i].getName());
        }
    }

    public static void copyFile(String srcDir, String desDir) throws IOException {
        FileInputStream in = new FileInputStream(srcDir);
        FileOutputStream out = new FileOutputStream(desDir);
        BufferedInputStream bin = new BufferedInputStream(in);
        BufferedOutputStream bout = new BufferedOutputStream(out);
        byte[] b = new byte[1024];
        int len;
        while ((len = bin.read(b)) != -1) {
            bout.write(b, 0, len);
        }
        bout.flush();
        bout.close();
        bin.close();
    }


}
